package com.kpmg.datalake.common.dynamicdatasource;

import com.alibaba.druid.util.JdbcConstants;

/**
 * 数据库类型配置
 *
 * @author alex.zhao
 * @see JdbcConstants
 */
public enum DBTypeEnum {
    /**
     * oracle
     */
    ORACLE(JdbcConstants.ORACLE, JdbcConstants.ORACLE_DRIVER, "jdbc:oracle:thin:@%s:%s/%s"),
    /**
     * mysql
     */
    MYSQL(JdbcConstants.MYSQL, JdbcConstants.MYSQL_DRIVER, "jdbc:mysql://%s:%s/%s"),
    /**
     * POSTGRESQL
     */
    POSTGRESQL(JdbcConstants.POSTGRESQL, JdbcConstants.POSTGRESQL_DRIVER, ""),
    /**
     * sqlserver
     */
    SQLSERVER(JdbcConstants.SQL_SERVER, JdbcConstants.SQL_SERVER_DRIVER, "jdbc:microsoft:sqlserver://%s:%s;DatabaseName=%s");

    private String dbType;
    private String driverClass;
    private String url;

    DBTypeEnum(String dbType, String driverClass, String url) {
        this.dbType = dbType;
        this.driverClass = driverClass;
        this.url = url;
    }

    public static DBTypeEnum getDbTypeEnum(String dbType) {
        for (DBTypeEnum dbTypeEnum : DBTypeEnum.values()) {
            if (dbType.toLowerCase().toLowerCase().contains(dbTypeEnum.dbType)) {
                return dbTypeEnum;
            }
        }
        return null;
    }

    public static String getDbType(String dbType) {
        for (DBTypeEnum dbTypeEnum : DBTypeEnum.values()) {
            if (dbType.toLowerCase().toLowerCase().contains(dbTypeEnum.dbType)) {
                return dbTypeEnum.getDbType();
            }
        }
        return null;
    }

    /**
     * 根据数据类型获取数据库驱动
     *
     * @param dbType 数据库类型
     * @return String
     */
    public static String getDriverClass(String dbType) {
        for (DBTypeEnum dbTypeEnum : DBTypeEnum.values()) {
            if (dbType.toLowerCase().toLowerCase().contains(dbTypeEnum.dbType)) {
                return dbTypeEnum.driverClass;
            }
        }
        return null;
    }

    /**
     * 根据数据类型获取数据库链接url
     *
     * @param dbType 数据库类型
     * @param ip     地址
     * @param port   端口
     * @param dbName 数据库
     * @return String
     */
    public static String getUrl(String dbType, String ip, String port, String dbName) {
        for (DBTypeEnum dbTypeEnum : DBTypeEnum.values()) {
            if (dbType.toLowerCase().toLowerCase().contains(dbTypeEnum.dbType)) {
                return String.format(dbTypeEnum.url, ip, port, dbName);
            }
        }
        return null;
    }

    public String getDbType() {
        return dbType;
    }

    public String getDriverClass() {
        return driverClass;
    }

    public String getUrl() {
        return url;
    }
}
